package com.icepeach.icepeachhomeback.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.icepeach.icepeachhomeback.entity.User;
import com.icepeach.icepeachhomeback.req.UserListQueryReq;
import com.icepeach.icepeachhomeback.service.UserService;
import com.icepeach.icepeachhomeback.util.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 获取所有用户
     *
     * @return
     */
    @PostMapping("/getAllUser")
    @ResponseBody
    public ApiResult getAllUser() {
        List<User> list = userService.list(null);
        return ApiResult.success("查询成功", list);
    }


    /**
     * 分页查询 获取用户
     *
     * @param userListQueryReq
     * @return
     */
    @PostMapping("/getUsersByPage")
    @ResponseBody
    public ApiResult getUsersByPage(@RequestBody UserListQueryReq userListQueryReq) {

        return ApiResult.success("查询成功", userService.getUsersByPage(userListQueryReq));
    }

    /**
     * 增加或修改用户
     * @param user
     * @return
     */

    @PostMapping("/saveUser")
    @ResponseBody
    public ApiResult saveUser(@RequestBody User user) {
        if(StrUtil.isBlank(user.getPassword())){
            user.setPassword("123456");
        }
        String password = SecureUtil.md5(user.getPassword());
        user.setPassword(password);

        boolean result = userService.saveOrUpdate(user);
        if (result) {
            return ApiResult.success("成功");
        } else {
            return ApiResult.failure("失败");
        }
    }

    @PostMapping("/deleteById")
    @ResponseBody
    public ApiResult deleteById(@RequestBody User user) {
        boolean result = userService.removeById(user.getId());

        if (result) {
            return ApiResult.success("成功");
        } else {
            return ApiResult.failure("失败");
        }
    }
    @PostMapping("/del/batch")
    @ResponseBody
    public ApiResult deleteBatch(@RequestBody List<String> ids) {
        userService.removeByIds(ids);
        return ApiResult.success("成功");
    }

}
